import 'package:flutter/material.dart';
import 'package:bts_toolbox/core/polyline_interpolator.dart';
import 'dart:math';

class BillingPage extends StatefulWidget {
  const BillingPage({super.key});
  @override
  State<BillingPage> createState() => _BillingPageState();
}

class _BillingPageState extends State<BillingPage>
    with AutomaticKeepAliveClientMixin {
  int _counter = 0;
  final String finalString = 'You have pushed the button\nthis many times:';
  String? _calculationResult = '';
  final TextEditingController _totalInvestmentController =
      TextEditingController();
  final TextEditingController _constructionCostController =
      TextEditingController();

  @override
  bool get wantKeepAlive => true;
  @override
  Widget build(BuildContext context) {
    super.build(context); // 调用父类的build方法
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _buildBillingResultColumn(), // 计费结果列
          _buildBillingInputRow(), // 计费输入行
        ],
      ),
    );
  }

  Expanded _buildBillingResultColumn() {
    return Expanded(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _billingResultText(), // 计费结果文本
          // _billingCounterText(), // 累计点击次数
        ],
      ),
    );
  }

  // Text _billingCounterText() {
  //   return Text(
  //     /// 累计点击次数文本
  //     '\n $_counter \n $_calculationResult',
  //     style: Theme.of(context).textTheme.headlineMedium?.copyWith(
  //       fontSize: 30,
  //       fontWeight: FontWeight.bold,
  //       fontStyle: FontStyle.normal,
  //     ),
  //   );
  // }

  Row _buildBillingInputRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      spacing: 5, // 增加间隙
      children: [
        _totalInvestmentInputText(), // 总投资输入文本
        _constructionCostInputText(), // 下浮率输入文本
        _rateCalculatorButton(), // 计算按钮
      ],
    );
  }

  SizedBox _totalInvestmentInputText() {
    return SizedBox(
      width: 130,
      height: 35,
      child: TextField(
        style: const TextStyle(fontSize: 13),
        maxLines: 1,
        controller: _totalInvestmentController,
        keyboardType: TextInputType.number,
        decoration: InputDecoration(
          labelText: '总投资',
          suffixText: ' 万元',
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(40),
            gapPadding: 3.0,
          ),
        ),
      ), // 总投资文本框
    );
  }

  SizedBox _constructionCostInputText() {
    return SizedBox(
      width: 130,
      height: 35,
      child: TextField(
        style: const TextStyle(fontSize: 13),
        maxLines: 1,
        controller: _constructionCostController,
        keyboardType: TextInputType.number,
        decoration: InputDecoration(
          labelText: '下浮率',
          suffixText: ' %',
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(40),
            gapPadding: 3.0,
          ),
        ),
      ), // 下浮率文本框
    );
  }

  SizedBox _rateCalculatorButton() {
    return SizedBox(
      width: 69,
      height: 35,
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.blue,
          foregroundColor: Colors.white,
          alignment: Alignment.center,
        ),
        child: const Text('Go'),
        onPressed: () {
          // 这里可以添加计费相关的操作
          _onPressCalculatorButton();
          // _billInterpolate();
        },
        onLongPress: () {
          // 这里可以添加长按相关的操作
          setState(() {
            _onLongPressCalculatorReset();
          });
        },
      ),
    );
  }

  Text _billingResultText() {
    return Text(
      /// 计费结果文本
      '$finalString\n$_counter\n$_calculationResult\n',
      // data:_allResult,
      textAlign: TextAlign.center,
      style: TextStyle(fontSize: 17),
    );
  }

  void _onPressCalculatorButton() {
    setState(() {
      _counter++;
      _billInterpolate();
    });
  }

  void _onLongPressCalculatorReset() {
    // 长按触发函数
    setState(() {
      _totalInvestmentController.clear();
      _constructionCostController.clear();
      _counter = 0;
      _calculationResult = '';
    });
  }

  void _billInterpolate() async {
    // 计费计算
    try {
      // 将文本转换为double类型，去掉多余的toString()调用
      double billAmount = double.parse(_totalInvestmentController.text);
      Billing billResult = Billing('she_ji_fei', billAmount);
      // 正确处理异步操作
      Point<double> result = await billResult.linearInterpolate();
      setState(() {
        _calculationResult = '计费结果：${result.y.toStringAsFixed(2)}万元';
      });
    } catch (e) {
      setState(() {
        _calculationResult = '请输入有效金额';
      });
    }
  }

  // void _counter() {
  //   int count = 0;
  //   count++;
  //   _counterResult = 'You have pushed the button\n this many times\n $count';
  // }
}
